package com.lagou.controller;

import com.alibaba.fastjson.JSONObject;
import com.lagou.pojo.Article;
import com.lagou.service.ArticleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

@Controller
public class ArticleController {

    @Autowired
    private ArticleService articleService;

    @RequestMapping("/index")
    public String getArticles(Model model, Integer page,Integer size) {

        if (null == page || page <= 0) {
            page = 1;
        }

        if (null == size || size <= 0) {
            size = 3;
        }

        Page<Article> articles = articleService.getArticles(page, size);
        int  totalElements = (int) articles.getTotalElements();
        //总页数

        int totalPage = totalElements % size == 0 ? totalElements / size :totalElements / size + 1;
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("pageList", articles);
        jsonObject.put("current", page);
        jsonObject.put("totalPage", totalPage);
        jsonObject.put("last", articles.getTotalPages());
        model.addAttribute("articles", jsonObject);
        return "/index";
    }
}
